package com.SmartCare.service.impl.medicine;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.SmartCare.common.enums.Constants;
import com.SmartCare.common.Result;
import com.SmartCare.common.exception.ServiceException;
import com.SmartCare.common.dto.medicine.MedicationDTO;
import com.SmartCare.service.medicine.MedicationService;
import com.SmartCare.mapper.medicine.MedicationFrequencyMapper;
import com.SmartCare.mapper.medicine.MedicationMapper;
import com.SmartCare.pojo.medicine.Medication;
import com.SmartCare.pojo.medicine.MedicationFrequency;
import com.SmartCare.utils.MedicationTransToDTO;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 用药情况表 服务实现类
 */
@Service
public class MedicationServiceImpl extends ServiceImpl<MedicationMapper, Medication> implements MedicationService {
    @Autowired
    private MedicationMapper medicationMapper;
    @Autowired
    private MedicationFrequencyMapper medicationFrequencyMapper;
    @Resource
    private MedicationTransToDTO medicationTransToDTO;

    /**
     * 所有药品名称查询 用于填充药物名称下拉框
     *
     * @return
     */
    @Override
    public Result medicineNameQuery() {
        List<Medication> medications = medicationMapper.selectList(null);
        List<String> nameList = new ArrayList<>();
        for (Medication item : medications) {
            nameList.add(item.getName());
        }
        return Result.success(nameList);
    }

    /**
     * 推荐药品信息查询
     *
     * @param name
     * @return
     */
    @Override
    public Result medicineQuery(String name) {
        if (!name.isEmpty() && name != null) {
            //查询信息
            Medication medication = super.getOne(new LambdaQueryWrapper<Medication>().eq(Medication::getName, name));
//            //封装返回对象
//            MedicationVo medicationVo = new MedicationVo();
//            //对给药频率字段进行处理 数字->字符串
//            BeanUtils.copyProperties(medication, medicationVo, "frequency_id", "mode");
//            MedicationFrequency medicationFrequency = medicationFrequencyMapper.selectById(medication.getFrequencyId());
//            medicationVo.setFrequency(medicationFrequency.getFrequency());
//            medicationVo.setMode(medication.getMode());
            if (medication != null) {
                return Result.success(medicationTransToDTO.trans(medication));
            } else {
                throw new ServiceException(Constants.CODE_400, "不存在该名称的药品信息");
            }
        }
        return Result.error();
    }


    @Override
    public Result addMedicine(Medication medication) {

        //对药品名称进行检查
        //判空
        if (medication.getName() == null || medication.getName().equals("")) {
            throw new ServiceException(Constants.CODE_400, "药品名称不能为空");
        }
        //查重
        Medication one = getOne(new QueryWrapper<Medication>().eq("name", medication.getName()));
        if (one != null) {
            throw new ServiceException(Constants.CODE_400, "该药品已存在，请勿重复添加");
        }
        //添加
        save(medication);

        return Result.success();
    }

    @Override
    public Result getAll(String careHomeName) {
        //先获取所有的药品对象
        List<Medication> list = list(new QueryWrapper<Medication>().eq("care_home_name", careHomeName));
        //将药品对象都转换成DTO对象
        List<MedicationDTO> result = new ArrayList<>();
        for (Medication medication : list) {
            result.add(medicationTransToDTO.trans(medication));
        }
        return Result.success(result);
    }

    @Override
    public Result edit(Medication medication) {
        //检查是否传入了id
        if (medication.getId() == null) {
            throw new ServiceException(Constants.CODE_400, "药品ID不能为空");
        }
        //检查id是否存在对应信息
        Medication one = getById(medication.getId());
        if (one == null) {
            throw new ServiceException(Constants.CODE_400, "不存在此ID的药品信息");
        }
        //检查是否有重复药名
        Medication getByName = getOne(new QueryWrapper<Medication>().eq("name", medication.getName()));
        if (getByName != null && !medication.getName().equals(one.getName())) {
            throw new ServiceException(Constants.CODE_400, "已存在该药品名称的药品信息，请修改药品名称");
        }
        //更新
        updateById(medication);

        return Result.success();
    }

    @Override
    public Result search(String keyword) {
        //先获取药品信息
        List<Medication> list = list(new QueryWrapper<Medication>().like("name", keyword));
        List<MedicationDTO> result = new ArrayList<>();
        for (Medication medication : list) {
            result.add(medicationTransToDTO.trans(medication));
        }
        return Result.success(result);
    }

    @Override
    public Result deleteById(Long id) {
        //判空
        if (id == null) {
            throw new ServiceException(Constants.CODE_400, "传入药品ID不能为空");
        }
        Medication one = getById(id);
        if (one == null) {
            throw new ServiceException(Constants.CODE_400, "不存在此ID的药品信息");
        }
        //删除
        removeById(id);
        return Result.success();
    }

    @Override
    public Result importMedication(MultipartFile file, String name) {

        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (row.getRowNum() == 0) {
                    continue;
                }
                Medication medication = new Medication();
                //名字查重
                if (getOne(new QueryWrapper<Medication>().eq("name", row.getCell(0).getStringCellValue())) != null) {
                    continue;
                }
                medication.setName(row.getCell(0).getStringCellValue());
                medication.setType(row.getCell(1).getStringCellValue());
                medication.setCareHomeName(name);
                //用药方式
                medication.setMode(row.getCell(2).getStringCellValue());
                //频率
                MedicationFrequency frequency = medicationFrequencyMapper.selectOne(new QueryWrapper<MedicationFrequency>().eq("frequency", row.getCell(3).getStringCellValue()));
                if (frequency != null) {
                    medication.setFrequencyId(frequency.getId());
                }
                if (row.getCell(4) == null) {
                    medication.setDosage(null);
                } else {
                    medication.setDosage(BigDecimal.valueOf(row.getCell(4).getNumericCellValue()));
                }

                medication.setUnit(row.getCell(5).getStringCellValue());

                save(medication);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Result.success();
    }

    @Override
    public void export(HttpServletResponse response, String name) {
        //查询药品数据
        List<Medication> medications = list(new QueryWrapper<Medication>().eq("care_home_name", name));
        //创建一个新的Excel工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet("Medications");

            //创建标题行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("药品名称");
            headerRow.createCell(1).setCellValue("药物剂型");
            headerRow.createCell(2).setCellValue("给药途径");
            headerRow.createCell(3).setCellValue("推荐给药频率");
            headerRow.createCell(4).setCellValue("推荐给药剂量");
            headerRow.createCell(5).setCellValue("推荐剂量单位");

            //填充数据行
            int rowNum = 1;
            for (Medication medication : medications) {
                Row dataRow = sheet.createRow(rowNum++);
                dataRow.createCell(0).setCellValue(medication.getName());
                if (medication.getType() != null) {
                    dataRow.createCell(1).setCellValue(medication.getType());
                }
                //用药途径
                if (medication.getMode() != null) {
                    dataRow.createCell(2).setCellValue(medication.getMode());
                }
                //频率
                if (medication.getFrequencyId() != null) {
                    MedicationFrequency fre = medicationFrequencyMapper.selectById(medication.getFrequencyId());
                    if (fre != null) {
                        dataRow.createCell(3).setCellValue(fre.getFrequency());
                    }
                }
                if (medication.getDosage() != null) {
                    dataRow.createCell(4).setCellValue(medication.getDosage().doubleValue());
                }
                if (medication.getUnit() != null) {
                    dataRow.createCell(5).setCellValue(medication.getUnit());
                }
            }
            //设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=MedicationsExport.xlsx");

            // 将工作簿内容写入响应输出流
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
